package com.example.starter.verticle;

import com.example.starter.conf.Constants;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetSocket;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangkui
 */
public class TCPVerticle extends AbstractVerticle {
  public static final String TCP_EVENT_BUS_ADDRESS = "tcp_event_bus";

  private final Map<String, NetSocket> map = new HashMap<>(64);

  @Override
  public void start() {

    var consumer = vertx.eventBus().<JsonObject>consumer(TCP_EVENT_BUS_ADDRESS);
    consumer.handler(message -> {
      var body = message.body();
      var type = body.getString(Constants.TYPE);
      var tmp = switch (type) {
        // 获取当前客户端在线数量
        case Constants.ONLINE -> map.size();
        // 向客户端发送消息
        case Constants.SEND -> "发送成功";
        //默认不做处理
        default -> new JsonObject();
      };
      var json = new JsonObject();

      json.put(Constants.TYPE, type);
      json.put(Constants.DATA, tmp);

      message.reply(json);
    });

    var conf = config().getJsonObject(Constants.TCP);
    @SuppressWarnings("all")
    var port = conf.getInteger(Constants.PORT);

    vertx.createNetServer().connectHandler(this::initSocket).listen(port)
      .onSuccess(server -> System.out.println("TCP server started on port " + port))
      .onFailure(e -> System.out.println("Failed to start TCP server: " + e.getMessage()));
  }

  private void initSocket(NetSocket socket) {
    var uuid = socket.writeHandlerID();
    map.put(uuid, socket);

    // 连接关闭移除连接
    socket.closeHandler(t -> {
      map.remove(uuid);
    });

    //连接发生异常关闭连接
    socket.exceptionHandler(e -> {
      System.out.println("Target connection: " + uuid + " happen error: " + e.getMessage());
      map.remove(uuid);
      socket.close();
    });
  }
}
